<?php
	
	require_once 'album.php';
	require_once 'image.php';
	require_once 'DAO.php';
	
	class AlbumDAO extends DAO {
		
		public function save ($albumName) {
			$album = new AlbumModel(null, $albumName, 0, array());
			$stmt = $this->db->prepare('INSERT INTO album (`name`, nb_images) VALUES (:name, 0)');
			$stmt->bindValue(':name', $album->getName());
			$stmt->execute();
		}
		
		public function getList() {
			$stmt = $this->db->query('	SELECT a.id AS aid, a.name, a.nb_images, i.id AS iid, i.path
										FROM album a
										LEFT JOIN album_image ai
											ON ai.id_album = a.id
										LEFT JOIN image i
											ON ai.id_image = i.id');
			$res = $stmt->fetchAll(PDO::FETCH_OBJ);
			$ret = array();
			foreach ($res as $r) {
				if (!isset($ret[$r->aid])) {
					$ret[$r->aid] = new AlbumModel($r->aid, $r->name, 0);
				}
				if (!is_null($r->iid)) {
					$img = new Image (DAO::urlPath.$r->path, $r->iid, null, null, $r->path, null, null);
					$ret[$r->aid]->addImg($img);
				}
			}
			return $ret;
		}
		
		public function getAlbum($aid) {
			$stmt = $this->db->prepare('SELECT a.id AS aid, a.name, a.nb_images, i.id AS iid, i.*
										FROM album a
										LEFT JOIN album_image ai
											ON ai.id_album = a.id
										LEFT JOIN image i
											ON ai.id_image = i.id
										WHERE a.id = :aid');
			$stmt->bindValue(':aid', $aid, PDO::PARAM_INT);
			$stmt->execute();
			$res = $stmt->fetchAll(PDO::FETCH_OBJ);
			$ret = array();
			foreach ($res as $r) {
				if (!isset($ret[$r->aid])) {
					$ret[$r->aid] = new AlbumModel($r->aid, $r->name, 0);
				}
				if (!is_null($r->iid)) {
					$img = new Image(DAO::urlPath.$r->path, $r->iid, $r->comment, $r->category, $r->path, $r->like, $r->unlike);
					$ret[$r->aid]->addImg($img);
				}
			}
			return current($ret);
		}
		
		public function addImg($aid, Image $img) {
			$stmt = $this->db->prepare('SELECT id_image FROM album_image WHERE id_album = :aid AND id_image = :iid');
			$stmt->bindValue(':aid', $aid, PDO::PARAM_INT);
			$stmt->bindValue(':iid', $img->getId(), PDO::PARAM_INT);
			$stmt->execute();
			if ($stmt->rowCount() === 0) {
				$stmt = $this->db->prepare('INSERT INTO album_image VALUES (:iid, :aid)');
				$stmt->bindValue(':aid', $aid);
				$stmt->bindValue(':iid', $img->getId());
				if ($stmt->execute()) {
					$stmt = $this->db->prepare('UPDATE album SET nb_images = nb_images+1 WHERE id=:id');
					$stmt->bindValue(':id', $aid);
					$stmt->execute();
				}
				
			}
		}
		
	}